package cn.fenqing.utils;

import cn.fenqing.annotation.ValidatorFiled;
import cn.fenqing.exception.ValidationObjectUtilsException;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fenqing
 */
public class ValidationObjectUtils {

    /**
     * 校验
     * @param o
     */
    public static void valid(Object o) {
        if(o == null){
            throw new NullPointerException();
        }
        Class<?> oClass = o.getClass();
        Field[] fields = oClass.getDeclaredFields();
        for (Field field : fields) {
            boolean annotationPresent = field.isAnnotationPresent(ValidatorFiled.class);
            Map<?, ?> map = new HashMap<>();
            if(annotationPresent){
                ValidatorFiled validatorFiled = field.getAnnotation(ValidatorFiled.class);
                Object value = ObjectUtils.getValue(o, field.getName());
                Strategy.ALL_STRATEGY.forEach(strategy -> {
                    if(!strategy.isSuccess(value, validatorFiled)){
                        throw new ValidationObjectUtilsException(String.valueOf(strategy.getClass().getSimpleName() + " : " +field));
                    }
                });
            }
        }
    }

    public static void main(String[] args) {
        User user = new User();
        valid(user);
    }

}

@Data
class User{
    @ValidatorFiled(isNull = false)
    private Integer id;
}

interface Strategy{

    List<Strategy> ALL_STRATEGY = new ArrayList<Strategy>(){{
        add(new IsNullStrategy());
    }};

    /**
     * 是否成功
     * @param value
     * @param validatorFiled
     * @return
     */
    boolean isSuccess(Object value, ValidatorFiled validatorFiled);
}

class IsNullStrategy implements Strategy {

    @Override
    public boolean isSuccess(Object value, ValidatorFiled validatorFiled) {
        boolean aNull = validatorFiled.isNull();
        if(aNull){
            return true;
        }else{
            return value != null;
        }
    }
}


class PatternStrategy implements Strategy {

    @Override
    public boolean isSuccess(Object value, ValidatorFiled validatorFiled) {
        String pattern = validatorFiled.pattern();
        if(value instanceof String){
            return ((String)value).matches(pattern);
        }else{
            return false;
        }
    }
}
